//
//  LoginViewController.m
//  TNS
//
//  Created by jadd on 16/2/1.
//  Copyright © 2016年 zhongyan. All rights reserved.
//

#import "LoginViewController.h"
#import "Masonry.h"
#import "GetTokenRequest.h"
#import "GetTokenResponse.h"
#import "RequestHandle.h"
#import "LoginRequest.h"
#import "LoginResponse.h"
#import "RefrashLoginRequest.h"
#import "RefrashLoginResponse.h"
#import "Config.h"
#import <QuartzCore/QuartzCore.h>
#import "SVWebViewController.h"
#import "PostcidRequest.h"
#import "PostcidResponse.h"
#import "UIColor+HEX.h"
#import "WebViewController.h"
#import "PrivacyViewController.h"
#import "AboutUsViewController.h"
#import "sys/utsname.h"
#import "HomeViewController.h"
#define fitScreenHeight (K_ScreenHeight/568)
#define K_Space   ([UIScreen mainScreen].bounds.size.width - 123) / 8
#define K_ScreenWidth [[UIScreen mainScreen] bounds].size.width
#define K_ScreenHeight [[UIScreen mainScreen] bounds].size.height
#define DEFAULT_LINE_GRAY_COLOR [UIColor colorWithRed:188.0/255 green:188.0/255  blue:188.0/255 alpha:0.6f]
#define UserPwd            @"userpwd"
#define Seleted            @"seleted"

@interface LoginViewController ()<UIGestureRecognizerDelegate>
@property (nonatomic,strong) NSString *token;
@property (nonatomic,strong) NSString *str;
@property (nonatomic,strong) UIButton *btn;
@end

@implementation LoginViewController
@synthesize userName,userPwd;
@synthesize isKeyBoardShowed;
- (NSString*)deviceString
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    NSLog(@"NOTE: Unknown device type: %@", deviceString);
    return deviceString;
}
- (UIButton *)btn {
    if (!_btn) {
        _btn = [[UIButton alloc] initWithFrame:CGRectZero];
    }
    return _btn;
}
-(void) setupUi
{
    //    [self setupLoginButton];
    [self setupNavBar];
    [self setupTapGesture];
    
}
-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
    {
        imageView.image=[UIImage imageNamed:imageName];
    }
    if (color)
    {
        imageView.backgroundColor=color;
    }
    
    return imageView;
}
-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField=[[UITextField alloc]initWithFrame:frame];
    
    textField.font=font;
    
    textField.textColor=[UIColor grayColor];
    
    textField.borderStyle=UITextBorderStyleNone;
    
    textField.placeholder=placeholder;
    
    return textField;
}

-(void)createTextFields
{
    NSString *Dev = [self deviceString];
    CGRect rect = CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight);
    
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:rect];
    backImageView.userInteractionEnabled = YES;
    [backImageView setImage:[UIImage imageNamed:@"loginBg"]];
    //    backImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    UIImageView *logoImgView = [[UIImageView alloc]init];
    if ([Dev isEqualToString:@"iPhone 4"] || [Dev isEqualToString:@"iPhone 4S"]) {
        logoImgView.frame = CGRectMake(30, K_ScreenHeight * 0.1, (K_ScreenWidth - 60), (K_ScreenWidth - 60) / 1.45);
    } else {
        logoImgView.frame = CGRectMake(30, K_ScreenHeight * 0.1, (K_ScreenWidth - 60), (K_ScreenWidth - 60) / 1.4);
    }
    logoImgView.contentMode =  UIViewContentModeScaleAspectFill;
    CALayer *layer= [logoImgView layer];
    //是否设置边框以及是否可见
    [layer setMasksToBounds:YES];
    //设置边框圆角的弧度
    //        [layer setCornerRadius:10.0];
    //设置边框线的宽
    [layer setBorderWidth:0.1];
    logoImgView.userInteractionEnabled = YES;
    [logoImgView setImage:[UIImage imageNamed:@"tns(1)_100"]];
    [backImageView addSubview:logoImgView];
    
    //登陆
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    if ([Dev isEqualToString:@"iPhone 4"] || [Dev isEqualToString:@"iPhone 4S"]) {
        [button setFrame:CGRectMake(25, K_ScreenHeight * 0.8, (K_ScreenWidth - 50), 45.0f)];
    } else {
        [button setFrame:CGRectMake(25, K_ScreenHeight * 0.72, (K_ScreenWidth - 50), 45.0f)];
    }
    [button.layer setMasksToBounds:YES];
    [button.layer setCornerRadius:5.0f];
    [button.layer setBorderWidth:0.5f];
    [button.layer setBorderColor:DEFAULT_LINE_GRAY_COLOR.CGColor];
    button.backgroundColor = [UIColor colorWithHexString:@"#EC008C"];
    
    [button setTitle:@"登  录" forState:UIControlStateNormal];
    UIFont *font = [UIFont systemFontOfSize:20.0];
    [button addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [button.titleLabel setFont:font];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backImageView addSubview:button];
    //记住密码
    
    self.btn.frame = CGRectMake(CGRectGetMinX(button.frame), CGRectGetMinY(button.frame) - 55, 20, 20);
    BOOL seleted = [[NSUserDefaults standardUserDefaults] boolForKey:Seleted];
    [self.btn addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
    if (seleted == YES) {
        [self.btn setImage:[UIImage imageNamed:@"remmber_selected"] forState:UIControlStateNormal];
    } else {
        [self.btn setImage:[UIImage imageNamed:@"remmber_unselect"] forState:UIControlStateNormal];
    }
    [self.btn setSelected:seleted];
    UILabel *leb = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.btn.frame) + 15, CGRectGetMinY(self.btn.frame), 60, 20)];
    leb.text = @"记住密码";
    leb.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(checkboxClick:)];
    [leb addGestureRecognizer:tap];
    leb.font = [UIFont systemFontOfSize:13];
    [backImageView addSubview:leb];
    leb.textColor = [UIColor colorWithHexString:@"#808080"];
    [backImageView addSubview:self.btn];
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.userInteractionEnabled = YES;
    [imageView setImage:[UIImage imageNamed:@"inputFrame"]];
    [backImageView addSubview:imageView];
    
    //top left bottom right
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.height.equalTo(@150);
        make.bottom.mas_equalTo(button.mas_top).with.offset(-70);
        make.left.offset(20);
        make.right.offset(-20);
        
    }];
    
    
    //账号
    UIImageView *Account = [[UIImageView alloc] init];
    [imageView addSubview:Account];
    [Account setImage:[UIImage imageNamed:@"username"]];
    [Account mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.top.offset(25);
        make.left.offset(10);
    }];
    
    
    
    userName = [[UITextField alloc] init];
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserDefault_uName];
    bool hasLogin = (uid == nil || [uid isEqualToString:@""]);
    if(hasLogin == NO)
    {
        userName.text =uid;
    }
    //userName.borderStyle = UITextBorderStyleRoundedRect;
    userName.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
    userName.clearButtonMode = UITextFieldViewModeWhileEditing;
    userName.font = [UIFont systemFontOfSize:18];
    userName.textColor = [UIColor grayColor];
    //userName.placeholder = @"用户名";
    [imageView addSubview:userName];
    
    [self.userName mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.size.mas_equalTo(CGSizeMake(30, 30));
        make.top.mas_equalTo(Account.mas_top).with.offset(4);
        make.left.mas_equalTo(Account.mas_right).with.offset(15);
        make.right.mas_equalTo(imageView.mas_right).with.offset(-35);
    }];
    
    
    ////密码
    UIImageView *userpassword = [[UIImageView alloc] init];
    [userpassword setImage:[UIImage imageNamed:@"password"]];
    [imageView addSubview:userpassword];
    
    [userpassword mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.left.mas_equalTo(Account.mas_left);
        make.top.mas_equalTo(Account.mas_bottom).with.offset(40);
    }];
    self.userPwd = [[UITextField alloc] init];
    //self.userPwd.borderStyle = UITextBorderStyleRoundedRect;
    self.userPwd .clearButtonMode = UITextFieldViewModeWhileEditing;
    self.userPwd.secureTextEntry = YES;
    self.userPwd .font = [UIFont systemFontOfSize:18];
    self.userPwd .textColor = [UIColor grayColor];
    NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:UserPwd];
    
    bool isselete = (password == nil || [password isEqualToString:@""]);
    if (isselete == NO && seleted == YES) {
        userPwd.text = password;
    }
    
    
    [imageView addSubview:self.userPwd];
    [self.userPwd  mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.size.mas_equalTo(CGSizeMake(30, 30));
        make.top.mas_equalTo(userpassword.mas_top);
        make.left.mas_equalTo(userpassword.mas_right).with.offset(15);
        make.right.mas_equalTo(imageView.mas_right).with.offset(-35);
    }];
    /*
    UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(K_Space, K_ScreenHeight - 45, 30, 30)];
    button1.layer.cornerRadius = 15;
    [button1 setBackgroundImage:[UIImage imageNamed:@"logobg"] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(tapLabel0:) forControlEvents:UIControlEventTouchUpInside];
    [backImageView addSubview:button1];
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(K_Space * 2 + 30, CGRectGetMinY(button1.frame), 1, 30)];
    view1.backgroundColor = [UIColor colorWithHexString:@"#808080"];
    [backImageView addSubview:view1];
    UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(view1.frame) + K_Space, CGRectGetMinY(button1.frame), 30, 30)];
    button2.layer.cornerRadius = 15;
    [button2 setBackgroundImage:[UIImage imageNamed:@"logobg"] forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(tapLabel1:) forControlEvents:UIControlEventTouchUpInside];
    [backImageView addSubview:button2];
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(button2.frame) + K_Space, CGRectGetMinY(button2.frame), 1, 30)];
    view2.backgroundColor = [UIColor colorWithHexString:@"#808080"];
    [backImageView addSubview:view2];
    UIButton *button3 = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(view2.frame) + K_Space, CGRectGetMinY(button2.frame), 30, 30)];
    button3.layer.cornerRadius = 15;
    [button3 setBackgroundImage:[UIImage imageNamed:@"logobg"] forState:UIControlStateNormal];
    [button3 addTarget:self action:@selector(tapLabel2:) forControlEvents:UIControlEventTouchUpInside];
    [backImageView addSubview:button3];
    UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(button3.frame) + K_Space, CGRectGetMinY(button2.frame), 1, 30)];
    view3.backgroundColor = [UIColor colorWithHexString:@"#808080"];
    [backImageView addSubview:view3];
    UIButton *button4 = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(view3.frame) + K_Space, CGRectGetMinY(button2.frame), 30, 30)];
    button4.layer.cornerRadius = 15;
    [button4 setBackgroundImage:[UIImage imageNamed:@"logobg"] forState:UIControlStateNormal];
    [button4 addTarget:self action:@selector(tapLabel3:) forControlEvents:UIControlEventTouchUpInside];
    [backImageView addSubview:button4];
     */
    [self.view addSubview:backImageView];//backImageView
    
}
-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait ;
}
-(BOOL)shouldAutorotate{
    return UIInterfaceOrientationIsLandscape(self.interfaceOrientation);
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
- (void)tapLabel0:(UIButton *)sender {
    HomeViewController *home = [[HomeViewController alloc] init];
    [self.navigationController pushViewController:home animated:YES];
}
- (void)tapLabel1:(UIButton *)sender {
    WebViewController *web = [[WebViewController alloc] init];
    [self.navigationController pushViewController:web animated:YES];
}
- (void)tapLabel2:(UIButton *)sender {
    PrivacyViewController *pri = [[PrivacyViewController alloc] init];
    [self.navigationController pushViewController:pri animated:YES];
}
-(void)tapLabel3:(UIButton *)sender {
    AboutUsViewController *us = [[AboutUsViewController alloc] init];
    [self.navigationController pushViewController:us animated:YES];
}
-(void)checkboxClick:(id *)sender {
    self.btn.selected = !self.btn.selected;
    BOOL hah = self.btn.selected;
    [[NSUserDefaults standardUserDefaults] setBool:hah forKey:Seleted];
    while (![[NSUserDefaults standardUserDefaults] synchronize])
    {
    }
    NSString *pwd = [self.userPwd.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [[NSUserDefaults standardUserDefaults] setObject:pwd forKey:UserPwd];
    
    if (self.btn.selected == YES) {
        [self.btn setImage:[UIImage imageNamed:@"remmber_selected"] forState:UIControlStateNormal];
    } else {
        [self.btn setImage:[UIImage imageNamed:@"remmber_unselect"] forState:UIControlStateNormal];
    }
    
    if (self.btn.selected) {
        NSString *pwd = [[NSUserDefaults standardUserDefaults] objectForKey:UserPwd];
        userPwd.text = pwd;
    }else {
        
    }
}
-(void) setupLoginButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setFrame:CGRectMake(25, K_ScreenHeight-(K_ScreenHeight/3), (K_ScreenWidth - 50), 45.0f)];
    
    [button.layer setMasksToBounds:YES];
    [button.layer setCornerRadius:5.0f];
    [button.layer setBorderWidth:0.5f];
    [button.layer setBorderColor:DEFAULT_LINE_GRAY_COLOR.CGColor];
    button.backgroundColor = [UIColor colorWithHexString:@"#EC008C"];
    [button setTitle:@"登  录" forState:UIControlStateNormal];
    UIFont *font = [UIFont systemFontOfSize:20.0];
    [button addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [button.titleLabel setFont:font];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [self.view addSubview:button];
}
-(void)getToken {
    GetTokenRequest *request = [[GetTokenRequest alloc] init];
    [RequestHandle startTokenWithRequest:request complete:^(id responseObject) {
        GetTokenResponse *response = [[GetTokenResponse alloc] init];
        response.responseObject = responseObject;
        self.token = [[NSString alloc] initWithData:response.responseObject encoding:NSUTF8StringEncoding];
        
        NSLog(@"%@",self.token);
    } error:^(NSError *error) {
        
    }];
}

- (void)loginAction:(UIButton *)sender {
    __weak LoginViewController *weakSelf = self;
    NSString *name = [self.userName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *pwd = [self.userPwd.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([name isEqualToString:@""]){
        [Config showMessage:@"用户名不能为空！"];
    }else if([pwd isEqualToString:@""]) {
        [Config showMessage:@"密码不能为空！"];
    }else{
        [Config showActivityView];
        LoginRequest *request = [[LoginRequest alloc] initWithUserName:name password:pwd];
        [RequestHandle startOperationWithRequest:request Token:self.token complete:^(id responseObject) {
            LoginResponse *response = [[LoginResponse alloc] init];
            response.responseObject = responseObject;
            NSLog(@"%@",responseObject);
            weakSelf.str = [responseObject objectForKey:@"token"];
            ViewController *vc = [[ViewController alloc] init];
            NSURL *URL = [NSURL URLWithString:@"http://www.autoyou.com.cn/home"];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; // 定义请求地址
            [request setValue:weakSelf.token forHTTPHeaderField:@"X-CSRF-TOKEN"];
            vc.token = weakSelf.str;
            //            [self.navigationController pushViewController:vc animated:YES];
            SVWebViewController *webViewController = [[SVWebViewController alloc] init];
            [[NSUserDefaults standardUserDefaults] setObject:name forKey:UserDefault_uName];
            webViewController.token = weakSelf.token;
            [self postcid];
            webViewController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:webViewController animated:YES];
            [Config hideActivityView];
        } error:^(NSError *error) {
            [Config showMessage:@"账号密码错误"];
            //            [Config hideActivityView];
        }];
        
    }
    
}
-(void)postcid {
    NSString *name = [self.userName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *cid = [[NSUserDefaults standardUserDefaults] objectForKey:@"clientId"];;//根据键值取出name
    PostcidRequest *request = [[PostcidRequest alloc] initWithUserName:name Cid:cid Type:@"ios"];
    [RequestHandle startTokenWithRequest:request complete:^(id responseObject) {
        PostcidResponse *response = [[PostcidResponse alloc] init];
        response.responseObject = responseObject;
    } error:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

-(void) setupNavBar
{
    self.navigationController.navigationBarHidden = true;
}

//键盘弹出，将界面上移
-(void) keyBoardWillShowUp: (NSNotification *) notification {
    
    NSDictionary *keyBoardInfo = notification.userInfo;
    
    if(keyBoardInfo != nil){
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.25];
        //CGRectMake(0, 160, K_ScreenWidth, K_ScreenHeight)
        [self.view setBounds:CGRectMake(0, 200, K_ScreenWidth, K_ScreenHeight)];
        self.view.frame = CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight);
        [UIView commitAnimations];
        isKeyBoardShowed = true;
    }
    
}
//恢复页面整体上移
-(void) keyBoardWillHide: (NSNotification *) notification {
    
    NSDictionary *keyBoardInfo = notification.userInfo;
    
    if(keyBoardInfo != nil){
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.25];
        
        [self.view setBounds:CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight)];
        self.view.frame = CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight);
        [UIView commitAnimations];
        isKeyBoardShowed = false;
    }
}



//添加手势，收回键盘使用
-(void) setupTapGesture {
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] init];
    [tapGesture addTarget:self action:@selector(pullDownKeyBoard)];
    [self.view addGestureRecognizer:tapGesture];
    
}
//    添加键盘通知方法
-(void) addKeyBoardNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShowUp:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

//移除键盘通知方法
-(void)  removeKeyBoardNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

-(void) pullDownKeyBoard {
    [userPwd resignFirstResponder];
    [userName resignFirstResponder];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUi];
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    self.navigationController.toolbarHidden = YES;
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    self.view.bounds = CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight);

    [self.view setFrame:CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight)];

    [self createTextFields];

    //    self.navigationController.hidesBarsOnSwipe = NO;
    [self getToken];
    CGRect rect = self.view.frame;
    NSLog(@"%@",self.view.frame);
    [[self navigationController] setNavigationBarHidden:YES];
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeNameNotification:) name:@"ChangeNameNotification" object:nil];
    [self addKeyBoardNotification];
    
}
-(void)ChangeNameNotification:(NSNotification*)notification{
    NSDictionary *nameDictionary = [notification userInfo];
    self.userName.text = [nameDictionary objectForKey:@"phone"];
    self.userPwd.text = [nameDictionary objectForKey:@"pwd"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeKeyBoardNotification];
    self.navigationController.navigationBarHidden = false;
}

-(void)viewDidDisappear:(BOOL)animated
{
    if(isKeyBoardShowed == true){
        [UIView commitAnimations];
        [self.view setBounds:CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight)];
    }
    
    //isKeyBoardShowed = false;
    
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
